<template>
  <div class="innerContainer">
    <common-title >
      <template #expand>
        <el-button type="primary" @click="onAdd">新增顶层节点</el-button>
      </template>
    </common-title>
    <div class="innerPane">
      <el-table
        :data="treeData"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'sub', hasChildren: 'hasChildren' }"
        style="width: 100%;"  row-class-name="fixed-row"
      >
        <el-table-column prop="deptName" label="部门名称" min-width="200" />
        <el-table-column prop="deptCode" label="部门编码" min-width="120" />
        <el-table-column prop="parentName" label="上级部门" min-width="120" />
        <el-table-column label="操作" min-width="200">
          <template #default="scope">
            <el-button type="primary" link @click="onAdd(scope.row)">新增子节点</el-button>
            <el-button type="primary" link @click="onEdit(scope.row)">修改</el-button>
            <el-button type="danger" link @click="onDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <edit-view ref="editViewRef" @success="search" @cancel="search" /> 
    </div> 
  </div>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

import {
  deptList,
  deptSave,
  deptDelete,
} from "../../utils/requests";
import EditView from "./EditView.vue";


const router = useRouter();
const currentDept = ref(null);


// Dom 挂载之后
onMounted(() => {
  search();
});



let treeData = ref([]);

const search = () => {
  currentDept.value = null;
  deptList().then((data) => {
    treeData.value = data;
  });
};

let editViewRef = ref(null);

const onAdd = (data) => {
  if (data) {
    currentDept.value = {
      id: null,
      deptName: "",
      parentCode: data.deptCode,
      parentName: data.deptName
    };
  } else {
    currentDept.value = {
      id: null,
      deptName: "",
      parentCode: null,
      parentName: "无"
    };
  }


  setTimeout(() => {
    editViewRef.value.setData(currentDept.value);
  }, 0);
}

const onEdit = (data) => {
  currentDept.value = { ...data };

  setTimeout(() => {
    editViewRef.value.setData(currentDept.value);
  }, 0);
};

const onDel = (data) => {
  if (data.sub && data.sub.length > 0) {
    ElMessage.error("请先删除子部门");
    return;
  }

  ElMessageBox.confirm(`确定删除${data.deptName}吗?`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deptDelete({ ids: data.id });

      ElMessage.success("删除成功");
      search();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
</script>

<style scoped lang="scss"> 
</style>
